package random.fox.p2p.presenter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.Date;
import java.util.List;

import flow.Flow;
import random.fox.p2p.Paths;
import random.fox.p2p.R;
import random.fox.p2p.bean.greendao.Message;
import random.fox.p2p.interactors.MessageInteractor;
import random.fox.p2p.interactors.OnAddActionListener;
import random.fox.p2p.interactors.OnLoadMessageListener;
import random.fox.p2p.ui.customview.CustomView;
import random.fox.p2p.ui.customview.imageLoader.CircleBitmapDisplayer;
import random.fox.p2p.util.Util;
import random.fox.p2p.view.IIndexView;

/**
 * Created by wq on 15/3/30.
 */
public class IndexPresenterImpl implements IndexPresenter, OnLoadMessageListener {
    private IIndexView indexView;
    private MessageInteractor interactor;
    private RecyclerView recyclerView;

    public IndexPresenterImpl(IIndexView indexView, MessageInteractor interactor) {
        this.indexView = indexView;
        this.interactor = interactor;
    }

    @Override
    public void loadData(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        List<Message> messages = interactor.getCacheData();
        if (messages != null && !messages.isEmpty()) {
            onSuccess(messages);
        } else {
            indexView.showProgress();
            interactor.loadMessage(this);
        }
    }

    @Override
    public void releaseData() {
        interactor.releaseHotData();
    }

    @Override
    public void onSuccess(List<Message> messages) {
        indexView.hideProgress();
        if (recyclerView != null) {
            MyRecycleAdapter adapter = new MyRecycleAdapter(messages);
            recyclerView.setAdapter(adapter);
        }
    }

    @Override
    public void onError(Throwable e) {
        indexView.hideProgress();
    }

    class MyRecycleAdapter extends RecyclerView.Adapter<MyRecycleAdapter.ViewHolder> {
        protected ImageLoader imageLoader = ImageLoader.getInstance();
        DisplayImageOptions options;
        private List<Message> messages;
        private Context context;

        public MyRecycleAdapter(List<Message> messages) {
            this.messages = messages;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            if (context == null)
                context = viewGroup.getContext();
            View view = View.inflate(context,
                    R.layout.item_view, null);
            ViewHolder holder = new ViewHolder(view);
            // 使用DisplayImageOptions.Builder()创建DisplayImageOptions
            options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.ic_launcher)
                    .showImageForEmptyUri(R.mipmap.ic_launcher)  // 设置图片Uri为空或是错误的时候显示的图片
                    .showImageOnFail(R.mipmap.ic_launcher)       // 设置图片加载或解码过程中发生错误显示的图片
                    .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                    .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                    .displayer(new CircleBitmapDisplayer())  // 设置成圆角图片
                    .build();
            return holder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
            final Message message = messages.get(i);
            imageLoader.displayImage("http://123.57.78.179:3000" + message.getHead_url(), viewHolder.headImageView, options);
           imageLoader.displayImage("http://123.57.78.179:3000" + message.getM_url(), viewHolder.customView.mImg);


            String nickname = message.getNickname();
            if (nickname == null)
                nickname = "游客";
            viewHolder.userNickname.setText(nickname);

            String status = "%s | 距离 %s";
            String distance = message.getLocation()==null?"未知":message.getLocation(); //没有进行计算
            viewHolder.status.setText(String.format(status, Util.times(message.getTime(), new Date()), distance));
            viewHolder.topic.setText("#" + message.getTheme() + "#");
            viewHolder.location.setText(message.getLocation());
            viewHolder.content.setText(message.getContent());
            if(message.getLikeCount() ==null) {
                viewHolder.edt_like.setText("0");
                message.setLikeCount(0);
            }else {
                viewHolder.edt_like.setText(message.getLikeCount() + "");
            }

            viewHolder.block_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (message.flag) {
                        Toast.makeText(context, "你已经赞过了:" + i, Toast.LENGTH_SHORT).show();
                    } else {
                        viewHolder.edt_like.setText((message.getLikeCount()+1)+"");
                        viewHolder.edt_like_anim.setVisibility(View.VISIBLE);
                        viewHolder.edt_like_anim.startAnimation(viewHolder.animation);
                        message.flag = true;
                        interactor.addLike(message.getMid() , new OnAddActionListener() {
                            @Override
                            public void onSuccess() {

                            }

                            @Override
                            public void onError(Throwable t) {

                            }
                        });
                    }
                }
            });

            viewHolder.block_reply.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Flow.get(v.getContext()).set(new Paths.ReplyPath(message.getMid()));
                }
            });

            viewHolder.block_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "i:" + i, Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public int getItemCount() {
            return messages.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView headImageView;
            public CustomView customView;
            public TextView userNickname, status, topic, location, content, edt_reply, edt_like, edt_like_anim;
            public RelativeLayout block_like, block_reply, block_share;

            public Animation animation = null;

            public ViewHolder(View itemView) {
                super(itemView);
                headImageView = (ImageView) itemView.findViewById(R.id.imv_user_head);
                customView = (CustomView) itemView.findViewById(R.id.custom_view);
                userNickname = (TextView) itemView.findViewById(R.id.tv_user_nickname);
                status = (TextView) itemView.findViewById(R.id.status);
                topic = (TextView) itemView.findViewById(R.id.topic);
                location = (TextView) itemView.findViewById(R.id.location);
                content = (TextView) itemView.findViewById(R.id.content);
                edt_reply = (TextView) itemView.findViewById(R.id.edt_reply);
                edt_like = (TextView) itemView.findViewById(R.id.edt_like);
                edt_like_anim = (TextView) itemView.findViewById(R.id.edt_like_anim);

                block_like = (RelativeLayout) itemView.findViewById(R.id.block_like);
                block_reply = (RelativeLayout) itemView.findViewById(R.id.block_reply);
                block_share = (RelativeLayout) itemView.findViewById(R.id.block_share);

                animation = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.zan);
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        edt_like_anim.setVisibility(View.VISIBLE);
                        Log.d("SSS", "onAnimationStart");
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        edt_like_anim.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });

            }


        }

    }
}
